package com.summer.core.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


/**
 * 解析xml帮助类
 * @author wwwlike
 * 
 */
public class XmlHelper {

    public static Document parseXml(File aFile) throws DocumentException {
        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(aFile);
        return doc;
    }

    public static Document parseXml(URL aURL) throws DocumentException {
        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(aURL);
        return doc;
    }
    
    /**
     * 解析xml
     * @param file 文件的绝对路径
     * @return Document对象
     * @throws DocumentException
     */
    public static Document parseXml(String file) throws DocumentException {
        File aFile = new File(file);
        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(aFile);
        return doc;
    }

    public static Document parseText(String xml) throws DocumentException {
        Document doc = DocumentHelper.parseText(xml);
        return doc;
    }
    
    /**
     * 保存一个document对象
     * @param document
     * @param path	文件的绝对路径
     * @param fileName	文件名称
     * @throws IOException
     */
    public static void saveXml(Document document,String path,String fileName) throws IOException {
        File path_file = new File(path);
        if(!path_file.exists())
            path_file.mkdirs();
        
        String file = path+"/"+fileName;
        // lets write to a file
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent("\t");
        XMLWriter writer = new XMLWriter(
            new OutputStreamWriter(new FileOutputStream(file,false),"UTF-8"),format
        );
        writer.write( document );
        writer.flush();
        writer.close();
    }
    
    /**
     * 保存一个document对象至xml
     * @param doc
     * @param file	文件绝对地址含文件名称
     * @throws Exception
     */
    public static void saveXml(Document doc,String file) throws Exception {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent("\t");
        XMLWriter writer = new XMLWriter(
            new OutputStreamWriter(new FileOutputStream(file,false),"UTF-8"),format
        );
        writer.write( doc );
        writer.flush();
        writer.close();
    }
}
